/**
 * 分页hock
 * @param  listRequestFn 请求函数
 * @param  initQuery 初始参数
 * @returns curPage, total, pageSize, list, updateData, searchQuery,loading,setLoading
 */

import { ref, watch, reactive } from "vue"
export default <T = any>(listRequestFn: Function, initQuery: any = {}) => {
  // 加载状态
  let loading = ref(false)
  // 页码
  const curPage = ref(1)
  // 总数量
  const total = ref(0)
  // 分页大小
  const pageSize = ref(10)
  //搜索参数
  const searchQuery = reactive<any>({})
  //数据
  const list = ref<T[]>([])

  const loadData = async (page: number = curPage.value, size: number = pageSize.value, _searchQuery?: any) => {
    setLoading(true)
    try {
      const {
        data: { total: count, list: data }
      } = await listRequestFn(page, size, _searchQuery)
      list.value = data
      total.value = count
    } finally {
      setLoading(false)
    }
  }
  const updateData = () => {
    loadData(curPage.value, pageSize.value, searchQuery)
  }

  const setLoading = (value: boolean) => {
    loading.value = value
  }

  //监听搜索参数的变化
  watch(searchQuery, () => {
    loadData(1, pageSize.value, { ...initQuery, ...searchQuery })
  })
  // 监听分页数据改变
  watch(
    [curPage, pageSize],
    () => {
      loadData(curPage.value, pageSize.value, { ...initQuery, ...searchQuery })
    },
    { immediate: true }
  )
  return { curPage, total, pageSize, list, updateData, searchQuery, loading, setLoading }
}
